package com.asman.base.lib.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.observers.ResourceObserver

/**
 * Created by yubaokang on 2017/2/6.
 */

object PermissionUtils {

    private val FILE_SETTING_CODE = 1000
    private val LOCAL_SETTING_CODE = 2000

    abstract class OnPermissionListener : OnPermissionL {
        override fun failed() {}
    }

    interface OnPermissionL {
        fun success()

        fun failed()
    }

    /**
     * 权限：读写存储
     *
     * @param activity Activity
     * @param listener OnPermissionListener
     */
    @SuppressLint("CheckResult")
    fun requestReadWriteSDCard(activity: FragmentActivity, listener: OnPermissionListener) {
        RxPermissions(activity)
            .request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE
            )//Manifest.permission.CAMERA,
            .subscribe { aBoolean ->
                if (aBoolean!!) {
                    listener.success()
                } else {
                    listener.failed()
                    showDialog(activity, "读写手机存储 权限被关闭，是否设置开启？", "取消", "设置", object :
                        ButtonClickListenerAbstract() {
                        override fun positiveButton() {
                            intentAppSetting(activity, FILE_SETTING_CODE)
                        }
                    })
                }
            }
    }

    /**
     * 定位权限
     *
     * @param activity Activity
     * @param listener OnPermissionListener
     */
    fun requestLocalPermission(activity: FragmentActivity, listener: OnPermissionListener) {
        RxPermissions(activity)
            .request(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            .subscribe(object : ResourceObserver<Boolean>() {
                override fun onNext(aBoolean: Boolean) {
                    if (aBoolean!!) {
                        listener.success()
                    } else {
                        listener.failed()
                        showDialog(activity, "定位权限被关闭,是否设置开启？", "取消", "设置", object :
                            ButtonClickListenerAbstract() {
                            override fun positiveButton() {
                                intentAppSetting(activity, LOCAL_SETTING_CODE)
                            }
                        })
                    }
                }

                override fun onError(e: Throwable) {}

                override fun onComplete() {}
            })
    }

    /**
     * 拍照，存储权限
     *
     * @param activity Activity
     * @param listener OnPermissionListener
     */
    @SuppressLint("CheckResult")
    fun requestCameraPermission(activity: FragmentActivity, listener: OnPermissionListener) {

        RxPermissions(activity)
            .request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA
            )
            .subscribe { aBoolean ->
                if (aBoolean!!) {
                    listener.success()
                } else {
                    listener.failed()
                    showDialog(activity, "拍照 或 读写存储权限被关闭,是否设置开启？", "取消", "设置", object :
                        ButtonClickListenerAbstract() {
                        override fun positiveButton() {
                            intentAppSetting(activity, FILE_SETTING_CODE)
                        }
                    })
                }
            }
    }

    /**
     * 权限：读写存储 手机状态
     *
     * @param activity Activity
     * @param listener OnPermissionListener
     */
    @SuppressLint("CheckResult")
    fun requestReadWriteSDCardAndPhoneState(
        activity: FragmentActivity,
        listener: OnPermissionListener
    ) {
        RxPermissions(activity)
            .request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE
            )
            .subscribe { aBoolean ->
                if (aBoolean!!) {
                    listener.success()
                } else {
                    listener.failed()
                    showDialog(activity, "读写手机状态 权限被关闭，是否设置开启？", "取消", "设置", object :
                        ButtonClickListenerAbstract() {
                        override fun positiveButton() {
                            intentAppSetting(activity, FILE_SETTING_CODE)
                        }
                    })
                }
            }


    }

    /**
     * 权限：手机状态
     *
     * @param activity Activity
     * @param listener OnPermissionListener
     */
    @SuppressLint("CheckResult")
    fun requestReadPhoneState(activity: FragmentActivity, listener: OnPermissionListener) {
        RxPermissions(activity)
            .request(Manifest.permission.READ_PHONE_STATE)
            .subscribe { aBoolean ->
                if (aBoolean!!) {
                    listener.success()
                } else {
                    listener.failed()
                    showDialog(activity, "读写手机状态 权限被关闭，是否设置开启？", "取消", "设置", object :
                        ButtonClickListenerAbstract() {
                        override fun positiveButton() {
                            intentAppSetting(activity, FILE_SETTING_CODE)
                        }
                    })
                }
            }
    }


    //跳转当前app应用信息界面
    fun intentAppSetting(context: Context, LOCAL_SETTING_CODE: Int) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", context.packageName, null)
        intent.data = uri
        if (context is Activity)
            context.startActivityForResult(intent, LOCAL_SETTING_CODE)
    }

    interface ButtonClickListener {
        fun neutralButton() //中性  取消等

        fun negativeButton() //消极：不同意，不满意，不合格等；

        fun positiveButton() //积极：合格，满意，同意，确定
    }

    abstract class ButtonClickListenerAbstract : ButtonClickListener {
        override fun negativeButton() {}

        override fun neutralButton() {}
    }

    fun showDialog(
        context: Context,
        title: String,
        negativeTxt: String,
        positiveTxt: String,
        listener: ButtonClickListener
    ) {
        val builder = AlertDialog.Builder(context)
        builder.setMessage(title)
            .setCancelable(true)
            .setNegativeButton(negativeTxt) { dialog, id ->
                dialog.cancel()
                listener.negativeButton()
            }
            .setPositiveButton(positiveTxt) { dialog, id ->
                dialog.cancel()
                listener.positiveButton()
            }
        val alert = builder.create()
        alert.show()
        //        AlertDialog创建之后才可以修改Button信息
        alert.getButton(AlertDialog.BUTTON_NEGATIVE)
            .setTextColor(Color.parseColor("#333333"))
        alert.getButton(AlertDialog.BUTTON_POSITIVE)
            .setTextColor(Color.parseColor("#D8364A"))
    }
}
